#include "Graphics.h"
#include "Scene.h"
#include "Camera.h"
#include "Node.h"
#include "UIText.h"

static Graphics* g_graphics = NULL;

Graphics* Graphics::GetGraphics()
{
	if (!g_graphics)
	{
		g_graphics = new Graphics();
	}

	return g_graphics;
}

Graphics::Graphics(void)
{
}

Graphics::~Graphics(void)
{
}

bool Graphics::Init( sf::Window* window )
{
	mCamera = new Camera();
	mWindow = window;
	return true;
}

void Graphics::Render()
{
	if (mCamera && mScene)
	{
		mCamera->Render(mScene);
	}
}

Node* Graphics::HitTest( int x, int y )
{
	GLuint buffer[128] = {0};
	glSelectBuffer(128, buffer);

	glRenderMode(GL_SELECT);

	mCamera->Render(mScene, true, x, y);

	glFlush();

	int hits = glRenderMode(GL_RENDER);

	if (hits)
	{
		GLuint* p = buffer;
		int selectedObjectID = -1;
		for (int i = 0; i < hits; i++)
		{
			int numID = *p++;
			p += 2;
			selectedObjectID = *p;
			p += numID;
		}
		Node* node = mScene->GetNodeByID(selectedObjectID);
		return node;
	}

	return NULL;
}

UIText* Graphics::UIHitTest( int x, int y )
{
	GLuint buffer[128] = {0};
	glSelectBuffer(128, buffer);

	glRenderMode(GL_SELECT);

	mCamera->Render(mScene, true, x, y);

	glFlush();

	int hits = glRenderMode(GL_RENDER);

	if (hits)
	{
		GLuint* p = buffer;
		int selectedObjectID = -1;
		for (int i = 0; i < hits; i++)
		{
			int numID = *p++;
			p += 2;
			selectedObjectID = *p;
			p += numID;
		}

		return mScene->GetTextByID(selectedObjectID);
	}

	return NULL;
}

